import {
  Controller,
  InternalServerErrorException,
  Post,
  UploadedFile,
  UseInterceptors
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import * as url from 'url'
import * as qiniu from 'qiniu'
import * as path from 'path'

@Controller('upload')
export class UploadController {
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    console.log(file)
    const mac = new qiniu.auth.digest.Mac(
      'PEVmaTQgXlhQKQ3kCsW84JytFLfvEcJsTTaOtyju',
      'ngqpSrGQYDviLJkb9qQnLDDfVnVZWPHd6aPAxDdh'
    )
    const putPolicy = new qiniu.rs.PutPolicy({
      scope: 'shuati-pro',
      expires: 7200
    })
    const uploadToken = putPolicy.uploadToken(mac)

    // uoload
    const formUploader = new qiniu.form_up.FormUploader(
      new qiniu.conf.Config({
        zone: qiniu.zone.Zone_z1
      })
    )

    const putExtra = new qiniu.form_up.PutExtra()

    // 获取file的扩展名
    const extname = path.extname(file.originalname)
    const fileKey = `${Date.now()}-${Math.floor(Math.random() * 1e8)}${extname}`

    return new Promise(_res => {
      formUploader.put(
        uploadToken,
        fileKey,
        file.buffer,
        putExtra,
        function (respErr, respBody, respInfo) {
          if (respErr) {
            console.error(respErr)
            throw new InternalServerErrorException(respErr.message)
          }

          if (respInfo.statusCode == 200) {
            _res(
              new url.URL(respBody.key, 'http://shuati.wangdashuai.top').href
            )
          } else {
            console.error(respInfo.statusCode, respBody)
            throw new InternalServerErrorException(respInfo)
          }
        }
      )
    })
  }
}
